import express from "express";
import path from "path";
import webpack from "webpack";
import webpackDevMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import React from "react";
import clientConfig from "../../webpack.client";
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import App from "@/shared/App";
const isDev = process.env.NODE_ENV === "development";
const app = express();
const port = process.env.PORT || 3000;
console.log(process.env.NODE_ENV)
// const compiler = webpack(clientConfig);
// app.use(webpackHotMiddleware(compiler));
// // 添加webpack开发中间件
// app.use(
//   webpackDevMiddleware(compiler, {
//     publicPath: "/",
//     stats: "minimal",
//   })
// );
// 静态资源服务
app.use(express.static(path.join(__dirname, "../dist/public")));

// HTML模板
const template = (content: string): string => `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React SSR with TypeScript</title>
</head>
<body>
  <div id="root">${content}</div>
  <script src="/main.js"></script>
</body>
</html>
`;

// 服务端渲染路由
app.get("*", (req, res) => {
  const content = renderToString(
    <StaticRouter location={req.url}>
      <App />
    </StaticRouter>
  );
  const html = template(content);
  res.send(html);
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
